package com.ssrs.platform.util;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.ssrs.platform.config.ResourceRoot;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传工具类
 *
 * @author ssrs
 */
public class FileUploadUtil {


    /**
     * 文件上传
     *
     * @param fie
     * @return
     */
    public static Map<String, Object> upload(MultipartFile fie) {
        String path = ResourceRoot.getValue();
        String fileName = "common/" + DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN) + "/" + System.currentTimeMillis();
        return upload(fie, path, fileName, false);
    }

    /**
     * 文件上传
     *
     * @param fie
     * @param path
     * @param fileName
     * @return
     */
    public static Map<String, Object> upload(MultipartFile fie, String path, String fileName, boolean rewrite) {
        Map<String, Object> result = new HashMap<>();

        if (path == null) {
            path = FileUtil.normalize(ResourceRoot.getValue());
        }
        if (fie == null) {
            result.put("Flag", false);
            result.put("Message", "文件不能为空");
            return result;
        }
        if (StrUtil.isEmpty(fileName)) {
            fileName = System.currentTimeMillis() + "";
        }
        String sourceFileName = fie.getOriginalFilename();
        String suffix = FileUtil.getSuffix(sourceFileName);

        fileName = fileName + "." + suffix;
        String fullName = path + "/" + fileName;
        fullName = FileUtil.normalize(fullName);
        if (!FileUtil.exist(new File(fullName).getParentFile())) {
            FileUtil.mkdir(new File(fullName).getParentFile());
        }
        if (!rewrite && new File(fullName).exists()) {
            result.put("Flag", false);
            result.put("Message", "文件已经存在");
            return result;
        }

        try {
            File diskFile = new File(fullName);
            fie.transferTo(diskFile);
            diskFile.setReadable(true, false);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("Flag", false);
            result.put("Message", e.getMessage());
            return result;
        }

        result.put("Flag", true);
        result.put("AbsolutePath", fullName);
        result.put("FileName", fileName);
        result.put("PreviewPath", "/preview/" + fileName);
        return result;
    }

    /**
     * 图片上传
     *
     * @param file 上传文件
     * @return
     */
    public static Map<String, Object> uploadImage(MultipartFile file) {
        return uploadImage(file, null);
    }

    /**
     * 图片上传
     *
     * @param file       上传文件
     * @param dimensions 生成多张缩略图，格式：100,100;200,200
     * @return
     */
    public static Map<String, Object> uploadImage(MultipartFile file, String dimensions) {
        String path = ResourceRoot.getValue();
        String fileName = "common/" + DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN) + "/" + System.currentTimeMillis();
        return uploadImage(file, path, fileName, false, dimensions);
    }


    /**
     * 图片上传
     *
     * @param file       上传文件
     * @param path       根路径
     * @param fileName   子路径
     * @param rewrite    是否重写
     * @param dimensions 生成多张缩略图，格式：100,100;200,200
     * @return
     */
    public static Map<String, Object> uploadImage(MultipartFile file, String path, String fileName, boolean rewrite, String dimensions) {
        Map<String, Object> result = new HashMap<>();

        if (path == null) {
            path = FileUtil.normalize(ResourceRoot.getValue());
        }
        if (file == null) {
            result.put("Flag", false);
            result.put("Message", "文件不能为空");
            return result;
        }
        if (StrUtil.isEmpty(fileName)) {
            fileName = System.currentTimeMillis() + "";
        }
        String sourceFileName = file.getOriginalFilename();

        String ext = FileTypes.checkAndGetExt(sourceFileName, "jpg", "jpeg", "bmp", "png", "gif");
        if (ext == null) {
            result.put("Flag", false);
            result.put("Message", "只能上传\"jpg,jpeg,bmp,png,gif\"格式的图片");
            return result;
        }

        String suffix = FileUtil.getSuffix(sourceFileName);

        fileName = fileName + "." + suffix;
        String fullName = path + "/" + fileName;
        fullName = FileUtil.normalize(fullName);
        if (!FileUtil.exist(new File(fullName).getParentFile())) {
            FileUtil.mkdir(new File(fullName).getParentFile());
        }
        if (!rewrite && new File(fullName).exists()) {
            result.put("Flag", false);
            result.put("Message", "文件已经存在");
            return result;
        }

        try {
            File diskFile = new File(fullName);
            file.transferTo(diskFile);
            diskFile.setReadable(true, false);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("Flag", false);
            result.put("Message", e.getMessage());
            return result;
        }
        if (StrUtil.isNotEmpty(dimensions)) {
            String[] arr = StrUtil.split(dimensions, ";");
            for (String dim : arr) {
                if (dim.indexOf(",") > 0) {
                    String w = dim.substring(0, dim.indexOf(","));
                    String h = dim.substring(dim.indexOf(",") + 1);
                    if (NumberUtil.isInteger(w) && NumberUtil.isInteger(h)) {
                        String prefix = fullName.substring(0, fullName.lastIndexOf("."));
                        String toFileName = prefix + "_" + w + "_" + h + "." + ext;
                        try {
                            ImgUtil.scale(new File(fullName), new File(toFileName), Integer.parseInt(w), Integer.parseInt(h), null);
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            e.printStackTrace();
                            result.put("Flag", false);
                            result.put("Message", e.getMessage());
                            return result;
                        }
                    }
                }
            }
        }

        result.put("Flag", true);
        result.put("AbsolutePath", fullName);
        result.put("FileName", fileName);
        result.put("PreviewPath", "/preview/" + fileName);
        return result;
    }

}
